package cluster

import akka.actor.Actor
import akka.cluster.Cluster
import akka.cluster.ClusterEvent._

/**
  * Created by shouf on 2016/5/17.
  */
class ClusterActor extends Actor  {
  val cluster = Cluster(context.system)

  override def preStart={
    //subscribe
    cluster.subscribe(self, initialStateMode = InitialStateAsEvents, classOf[MemberEvent], classOf[UnreachableMember])
  }

  override def postStop={
    //unsubscribe
    cluster.unsubscribe(self)
  }

  override def receive={
    case mu: MemberUp => println(s"member up:${mu.member.address}")
      println(s"leader:${cluster.state.leader.get}\r\n members:")
      cluster.state.members.foreach(s => println(s.address))
      println("members end");
    case um: UnreachableMember => println(s"UnreachableMember: ${um.member.address}")
    case mr: MemberRemoved => println(s"MemberRemoved is Removed: ${mr.member.address} after  ${mr.previousStatus}")
    case str:String => println(s"cluster:${sender().path}  ${str}")

  }
}
